package renderStrategy;

import javax.swing.JPanel;

import performanceProfiling.PerformanceProfiling;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import main.GameTree;
import main.Commons;
import main.Board;


public class RenderStrategy implements Commons{
	
	private BufferedImage offImg1;
	private BufferedImage offImg2;
	private BufferedImage offImg;
	GameTree gameTree;
	
	public RenderStrategy(){
		
	}
	
	public synchronized void notifyReDraw(GameTree gameTree){
		this.gameTree = gameTree;
		notifyAll();
	}
	
	public Graphics2D createBuffer(boolean cycleA, JPanel b, PerformanceProfiling profiles, boolean debug) {
	    Graphics2D g2 = null;
	    offImg = offImg1;
	    if(cycleA){
	    	offImg = offImg2;
	    }	    
	    if (offImg == null || offImg.getWidth() != b.getSize().width
	        || offImg.getHeight() != b.getSize().height) {
	      offImg = (BufferedImage) b.createImage(b.getSize().width, b.getSize().height);
	    }
	    if (offImg != null) {
	      g2 = offImg.createGraphics();
	      g2.setBackground(b.getBackground());
	    }
	    if(g2 != null){
	    	g2.clearRect(0, 0, b.getSize().width, b.getSize().height);
	    }	 
	    return g2;
	 
	  }
	
	public synchronized void render(boolean cycleA, Board b, PerformanceProfiling profiles, boolean debug){
		while(true){
			try{				
				wait();		
			}catch(InterruptedException e){}
			Graphics2D g2d = createBuffer(cycleA,  b, profiles, debug);
			if(g2d != null){
				if(cycleA){
					synchronized(gameTree.drawTreeB){
						
						b.paint(g2d);
						ImageObserver image_observer = b;
						g2d.setRenderingHints(text_antialising);
						g2d.setRenderingHints(alpha_interp);
						g2d.setRenderingHints(key_rendering);
						g2d.setRenderingHints(key_color_rendering);
						gameTree.drawEveryThing(g2d, image_observer, cycleA);
						if(debug){
							profiles.printToScreen(g2d, 0, 0);
						}
						g2d.dispose();
						if (offImg != null && b.isShowing()) {
							b.getGraphics().drawImage(offImg, 0, 0, b);
						}
						cycleA = !cycleA;
					}
				}
				else{
					synchronized(gameTree.drawTreeA){
						
						b.paint(g2d);
						ImageObserver image_observer = b;
						g2d.setRenderingHints(text_antialising);
						g2d.setRenderingHints(alpha_interp);
						g2d.setRenderingHints(key_rendering);
						g2d.setRenderingHints(key_color_rendering);
						gameTree.drawEveryThing(g2d, image_observer, cycleA);
						if(debug){
							profiles.printToScreen(g2d, 0, 0);
						}
						g2d.dispose();
						if (offImg != null && b.isShowing()) {
							b.getGraphics().drawImage(offImg, 0, 0, b);
						}
						cycleA = !cycleA;
					}
				}		
			}
		}
	}
	

}
